package com.zfzs.post.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.zfzs.post.ali.AliOssUtils;
import com.zfzs.post.aop.log.Log;
import com.zfzs.post.common.bean.ResponseResult;
import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.modules.agent.service.dto.AgentDTO;
import com.zfzs.post.modules.domain.Picture;
import com.zfzs.post.service.JwtUserDetailsService;
import com.zfzs.post.service.PictureService;
import com.zfzs.post.utils.FileUtil;
import com.zfzs.post.utils.SecurityUtils;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wq
 * @date 2019/9/24 15:54
 * @description 图片上传接口
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;


    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log("上传图片")
    @PostMapping(value = "/picture")
    public ResponseResult picture(@RequestParam MultipartFile file, String path) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long agentId = agent.getId();
        String userId = String.valueOf(agentId);
        String url = "";
        try {
            InputStream input = file.getInputStream();
            String names = file.getOriginalFilename();
            String suffix = names.substring(names.lastIndexOf("."));
            String imgId = StringUtils.getDateString(5);
            url = AliOssUtils.uploadBytes(input, path + "/" + imgId + suffix);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        Long id = snowflake.nextId();
        pictureService.save(id, url, String.valueOf(userId));
        map.put("imgId", id);
        return ResponseResult.ok("上传成功", map);
    }

    /**
     * 上传图片(身份证)
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/uploadMap")
    public ResponseResult uploadMap(@RequestBody Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>(params.size());
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long agentId = agent.getId();
        String userId = String.valueOf(agentId);
        String url;
        String path = params.get("path").toString();
        if (StringUtils.isBlank(path)) {
            throw new BadRequestException("文件上传路径不能为空");
        }
        params.remove("path");

        if (params.get("positive") == null) {
            throw new BadRequestException("请上传身份证正面照片");
        }

        if (params.get("reverse") == null) {
            throw new BadRequestException("请上传身份证反面照片");
        }

        if (params.get("positive").toString().length() < 30) {
            throw new BadRequestException("请上传身份证正面照片");
        }

        if (params.get("reverse").toString().length() < 30) {
            throw new BadRequestException("请上传身份证反面照片");
        }

        try {

            for (Map.Entry<String, Object> entry : params.entrySet()) {

                String base64 = params.get(entry.getKey()).toString();

                if (!base64.contains(";base64,")) {
                    continue;
                }
                String suffix = base64.substring(base64.indexOf("data:image/") + 11, base64.indexOf(";base64,"));

                String base64Str = base64.replace("data:image/" + suffix + ";base64,", "");

                byte[] bytes = new BASE64Decoder().decodeBuffer(base64Str.trim());

                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

                String imgId = StringUtils.getDateString(5);

                url = AliOssUtils.uploadBytes(inputStream, path + "/" + imgId + "." + suffix);

                Snowflake snowflake = IdUtil.createSnowflake(1, 1);

                Long id = snowflake.nextId();

                pictureService.save(id, url, String.valueOf(userId));

                map.put(entry.getKey(), id);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (map.get("positive") == null || map.get("reverse") == null) {
            throw new BadRequestException("照片上传失败");
        }


        return ResponseResult.ok("上传成功", map);
    }


}
